#!/bin/bash

WAR=ehuser-$2-SNAPSHOT.war

LANG=en_US.UTF-8
export LANG

getpid() {
    local i
    for i in $(ps -elf | grep "ehuser" | grep -v grep | awk '{print $4}')
    do
        echo "$i"
    done
}

start(){
    local PID=$(getpid)
    if [ "$PID" = "" ]; then
        nohup java -Xmx512m -jar ${WAR} --spring.config.name=config --logging.config=logback.xml >/dev/null 2>&1 &
    else
        echo "Server is already running"
    fi
}

restart(){
    local PID=$(getpid)
    if [ "$PID" = "" ]; then
        start
    else
        stop
        sleep 5
        start
    fi
}

stop(){
    local PID=$(getpid)
    if [ "$PID" = "" ]; then
        echo "Server is not running"
    else
        kill ${PID}
        sleep 2
    fi
}

status(){
    local PID=$(getpid)
    local se=$$

    echo "pid = $PID"
    echo "ddd = $se"

    if [ "$PID" = "" ]; then
        echo "Server is not running"
    else
        echo "Server is running"
    fi
}


usage(){
    echo "Usage: $0 {start|stop|status|restart} <version>"
}

case $1 in
    start)
        if [ ! -e ${WAR} ]; then
          echo "Server is not properly installed"
        else
            start
        fi
        ;;
    restart)
        if [ ! -e ${WAR} ]; then
          echo "Server is not properly installed"
        else
            restart
        fi
        ;;
    stop)
        stop
        ;;
    status)
        status
        ;;
    *)
        usage
esac
